package com.example.cm_player.service

import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Binder
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import com.example.cm_player.model.SongInfo
import com.example.cm_player.IMusicPlayer
import com.example.cm_player.model.PlayMode
import com.example.cm_player.manager.PlayerManager
import com.example.cm_player.manager.PlayerStateManager


/**
 * 音乐播放服务，管理后台播放和通知
 */
class PlayerService : Service(), IMusicPlayer, PlayerManager.NotificationController {
    private val binder = PlayerBinder()
    val playerManager: PlayerManager by lazy { PlayerManager.getInstance()}.apply {
        this.value.setNotificationController(this@PlayerService)
    }
    private val notificationHelper: NotificationHelper by lazy { NotificationHelper.getInstance() }
    private var isReceiverRegistered = false
    private var isShow = false
    private val isPlayingObserver:Observer<Boolean> = Observer<Boolean> {
        if(isShow) {
            updateNotification()
        }
    }

    private val notificationReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                NotificationHelper.ACTION_PLAY -> {
                    updateNotificationPlayState(true)
                    resume()
                }
                NotificationHelper.ACTION_PAUSE -> {
                    updateNotificationPlayState(false)
                    pause()
                }
                NotificationHelper.ACTION_PREVIOUS -> previousMusic()
                NotificationHelper.ACTION_NEXT -> nextMusic()
                NotificationHelper.ACTION_CLOSE -> {
                    isShow = false
                    pause()
                }
            }
        }
    }
    override fun onCreate() {
        super.onCreate()
        playerManager.createNewPlayer()
        PlayerStateManager.isPlaying.observeForever(isPlayingObserver)
        try {
            val mainActivityClass = Class.forName("com.example.cloudmusic.MainActivity")
            notificationHelper.init(this, mainActivityClass)
        } catch (e: ClassNotFoundException) {
            notificationHelper.init(this, this.javaClass)
        }

        registerNotificationReceiver()
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 如果当前有正在播放的歌曲，显示通知
       PlayerStateManager.currentPlayedMusic.value?.let { songInfo ->
            val isPlaying = PlayerStateManager.isPlaying.value ?: false
            showPlayingNotification(songInfo, isPlaying)
        }

        return START_STICKY
    }
    
    /**
     * 显示播放通知
     */
    private fun showPlayingNotification(songInfo: SongInfo, isPlaying: Boolean) {
        val notification = notificationHelper.createNotification(
            this,
            songInfo,
            isPlaying,
            this::createActionPendingIntent
        )
        
        if (isPlaying) {
            startForeground(notificationHelper.getNotificationId(), notification)
        } else {
            stopForeground(false)
            notificationHelper.showNotification(notification)
        }
    }
    
    /**
     * 更新通知播放状态
     */
    private fun updateNotificationPlayState(isPlaying: Boolean) {
        PlayerStateManager.currentPlayedMusic.value?.let { songInfo ->
            if (isPlaying) {
                val notification = notificationHelper.createNotification(
                    this,
                    songInfo,
                    true,
                    this::createActionPendingIntent
                )
                startForeground(notificationHelper.getNotificationId(), notification)
            } else {
                notificationHelper.updatePlaybackState(false, this::createActionPendingIntent)
                stopForeground(false)
            }
        }
    }
    
    /**
     * 创建操作的PendingIntent
     */
    private fun createActionPendingIntent(action: String): PendingIntent {
        val intent = Intent(action)
        return PendingIntent.getBroadcast(
            this,
            getRequestCode(action),
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
    }
    
    /**
     * 根据操作获取请求码
     */
    private fun getRequestCode(action: String): Int {
        return when (action) {
            NotificationHelper.ACTION_PLAY, NotificationHelper.ACTION_PAUSE -> 1
            NotificationHelper.ACTION_PREVIOUS -> 2
            NotificationHelper.ACTION_NEXT -> 3
            NotificationHelper.ACTION_CLOSE -> 4
            else -> 0
        }
    }
    
    /**
     * 注册通知广播接收器
     */
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun registerNotificationReceiver() {
        if (!isReceiverRegistered) {
            val filter = IntentFilter().apply {
                addAction(NotificationHelper.ACTION_PLAY)
                addAction(NotificationHelper.ACTION_PAUSE)
                addAction(NotificationHelper.ACTION_PREVIOUS)
                addAction(NotificationHelper.ACTION_NEXT)
                addAction(NotificationHelper.ACTION_CLOSE)
            }
            registerReceiver(notificationReceiver, filter, RECEIVER_NOT_EXPORTED)
            isReceiverRegistered = true
        }
    }
    
    /**
     * 注销通知广播接收器
     */
    private fun unregisterNotificationReceiver() {
        if (isReceiverRegistered) {
            try {
                unregisterReceiver(notificationReceiver)
                isReceiverRegistered = false
            } catch (e: Exception) {
                // 接收器可能已经注销
            }
        }
    }

    override fun onDestroy() {
        PlayerStateManager.isPlaying.removeObserver(isPlayingObserver)
        unregisterNotificationReceiver()
        notificationHelper.cancelNotification()
        isShow = false
        notificationHelper.release()
        playerManager.release()
        super.onDestroy()
    }

    /**
     * Service绑定对象
     */
    inner class PlayerBinder : Binder() {
        fun getService(): PlayerService = this@PlayerService
    }

    override fun play(songInfo: SongInfo) {
        if(!isShow){
            showPlayingNotification(songInfo, true)
            isShow = true
        }
        playerManager.play(songInfo)
    }

    override fun start() {
        playerManager.start()
    }

    override fun pause() {
        playerManager.pause()
    }

    override fun resume() {
        isShow = true
        playerManager.resume()
    }

    override fun stop() {
        playerManager.stop()
        stopForeground(true)
        isShow = false
        notificationHelper.cancelNotification()
    }

    override fun seekTo(position: Long) {
        playerManager.seekTo(position)
    }

    override fun setVolume(volume: Float) {
        playerManager.setVolume(volume)
    }

    override fun previousMusic() {
        playerManager.previousMusic()
    }

    override fun nextMusic() {
        playerManager.nextMusic()
    }

    override fun addToPlaylist(songInfo: SongInfo) {
        playerManager.addToPlaylist(songInfo)
    }

    override fun removeFromPlaylist(songInfo: SongInfo) {
        playerManager.removeFromPlaylist(songInfo)
    }

    override fun addNewPlayList(newList: List<SongInfo>) {
        playerManager.addNewPlayList(newList)
    }

    override fun getCurrentMusicList() = playerManager.getCurrentMusicList()

    override fun clearMusicPlayList() {
        playerManager.clearMusicPlayList()
    }

    override fun setPlayMode(playMode: PlayMode) {
        playerManager.setPlayMode(playMode)
    }

    override fun getPlayMode() = playerManager.getPlayMode()

    override fun release() {
        playerManager.release()
    }

    override fun updateNotification() {
            updateNotificationPlayState(PlayerStateManager.isPlaying.value!!)
    }

} 
